const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');
const fs = require('fs');
const multer = require('multer');

// 尝试加载环境变量配置，如果文件不存在则跳过
try {
  require('dotenv').config();
} catch (err) {
  console.log('未找到.env文件，将使用默认配置');
}

// 引入路由
const healthCardRoutes = require('./routes/healthCard');
const uploadRoutes = require('./routes/upload');

// 导入数据库配置
const db = require('./config/database');

const app = express();
const PORT = process.env.PORT || 3000;

// 创建上传目录
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// 中间件
app.use(cors());
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));
app.use('/api/uploads', express.static(path.join(__dirname, 'uploads')));
app.use(express.static(path.join(__dirname, '../public')));

// 路由
app.use('/api/health-cards', healthCardRoutes);
app.use('/api/upload', uploadRoutes);

// 将所有前端路由重定向到index.html
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '../public/index.html'));
});

// 测试数据库连接
db.query('SELECT 1 + 1 AS solution', (err, results) => {
  if (err) {
    console.error('数据库连接失败:', err);
  } else {
    console.log('数据库连接成功!');
    
    // 启动服务器
    app.listen(PORT, () => {
      console.log(`服务器运行在 http://localhost:${PORT}`);
    });
  }
});

// 错误处理
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: '服务器错误', message: err.message });
}); 